package com.feonix.common.util.mvc;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import com.feonix.common.BaseInfo;
import com.feonix.common.util.FileUtil;
import com.feonix.common.util.SpringUtil;
import com.feonix.common.util.StringUtil;
import com.feonix.common.util.mvc.ControllerUtil;
import com.feonix.common.util.mvc.FileResource;

public class ControllerUtil {
	private static final Log logger = LogFactory.getLog(ControllerUtil.class);

	private static final String[] ieFeatures = { "msie", "trident" };

	/**
	 * 获得下载的文件
	 * 
	 * @param file
	 * @param fileName
	 * @return
	 */
	public static FileResource getFileResource(File file, String fileName) {
		String userAgent = SpringUtil.getRequest().getHeader("user-agent");
		if (StringUtil.isNotEmpty(userAgent)) {
			userAgent = userAgent.toLowerCase();
		}
		boolean isIEFeature = false;
		for (String ieFeature : ieFeatures) {
			if (StringUtil.contains(userAgent, ieFeature)) {
				isIEFeature = true;
				break;
			}
		}

		HttpHeaders httpHeaders = new HttpHeaders();
		MediaType mediaType = new MediaType("application", "octet-stream");
		httpHeaders.setContentType(mediaType);
		try {
			if (isIEFeature) {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} else {
				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			}
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
			unsupportedEncodingException.printStackTrace();
		}
		httpHeaders.setContentDispositionFormData("attachment", fileName);
		byte[] fileBytes = null;
		try {
			fileBytes = FileUtils.readFileToByteArray(file);
		} catch (IOException IOException) {

		}
		FileResource fileResource = new FileResource(fileBytes, httpHeaders, HttpStatus.OK);
		return fileResource;
	}

	/**
	 * 将multipartFile写入目标文件
	 * 
	 * @param file
	 * @param multipartFile
	 * @return
	 */
	public static boolean writeMultipartFileToFile(File file, MultipartFile multipartFile) {
		boolean isSuccess = false;
		try {
			if ((multipartFile == null) || (multipartFile.isEmpty())) {
				return isSuccess;
			}
			if (!(file.exists())) {
				FileUtil.createFile(file);
			}
			multipartFile.transferTo(file);
			isSuccess = true;
		} catch (Exception exception) {
			logger.error("writeMultipartFileToFile error", exception);
		}
		return isSuccess;
	}

	/**
	 * 直接读取multipartFile 到string
	 * 
	 * @param multipartFile
	 * @return
	 */
	public static String readMultipartFileToString(MultipartFile multipartFile) {
		String str = null;
		try {
			if ((multipartFile == null) || (multipartFile.isEmpty())) {
				return str;
			}
			str = IOUtils.toString(multipartFile.getInputStream(), "utf-8");
		} catch (Exception exception) {
			logger.error("readMultipartFileToString error", exception);
		}
		return str;
	}

	/**
	 * 输出字符串
	 * 
	 * @param str
	 * @param response
	 */
	public static void showString(String str, HttpServletResponse response) {
		render(response, "text/plain", str, new String[0]);
	}

	/**
	 * 输出html
	 * 
	 * @param str
	 * @param response
	 */
	public static void showHtml(String str, HttpServletResponse response) {
		render(response, "text/html", str, new String[0]);
	}

	/**
	 * 输出json
	 * 
	 * @param str
	 * @param response
	 */
	public static void showJson(String str, HttpServletResponse response) {
		render(response, "application/json", str, new String[0]);
	}

	/**
	 * 输出xml
	 * 
	 * @param str
	 * @param response
	 */
	public static void showXml(String str, HttpServletResponse response) {
		render(response, "text/xml", str, new String[0]);
	}

	/**
	 * 已过时。
	 * 
	 * @param str
	 * @return
	 */
	@Deprecated
	public static String getAlterScript(String str) {
		return "<script type=\"text/javascript\">top.alert(\"" + str + "\");</script>";
	}

	@Deprecated
	public static String getScript(String[] strs) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("<script type=\"text/javascript\" src=\"");
		stringBuffer.append(BaseInfo.getContextPath());
		stringBuffer.append("/jquery/jquery.min.js\"></script>\n");
		stringBuffer.append("<script type=\"text/javascript\" src=\"");
		stringBuffer.append(BaseInfo.getContextPath());
		stringBuffer.append("/resources/script/ui.js\"></script>\n");
		stringBuffer.append("<script type=\"text/javascript\">");
		for (String str : strs) {
			stringBuffer.append(str);
			stringBuffer.append(";");
		}
		stringBuffer.append("</script>\n");
		return stringBuffer.toString();
	}

	public static void render(HttpServletResponse response, String contentType, String content, String[] headers) {
		try {
			String charset = "UTF-8";
			boolean bool = true;
			for (String header : headers) {
				String str2 = StringUtils.substringBefore(header, ":");
				String str3 = StringUtils.substringAfter(header, ":");

				if (StringUtils.equalsIgnoreCase(str2, "encoding:"))
					charset = str3;
				else if (StringUtils.equalsIgnoreCase(str2, "no-cache:"))
					bool = Boolean.parseBoolean(str3);
				else {
					throw new IllegalArgumentException(str2 + "不是一个合法的header类型");
				}
			}

			String str1 = contentType + ";charset=" + charset;
			response.setContentType(str1);
			if (bool) {
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0L);
			}
			response.getWriter().write(content);
		} catch (IOException IOException) {
			logger.error(IOException.getMessage(), IOException);
		}
	}

	/**
	 * 获取cookie值的静态方法
	 * 
	 * @param name
	 * @return
	 */
	public static String getCookieValue(String name) {
		Cookie[] cookies = SpringUtil.getRequest().getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					return StringUtil.decoder(cookie.getValue());
				}
			}
		}
		return "";
	}

	public static void addCookie(HttpServletResponse response, String key, String value, int seconds) {
		addCookie(response, key, value, seconds, null);
	}

	public static void addCookie(HttpServletResponse response, String key, String value, int seconds, String path) {
		Cookie cookie = new Cookie(key, StringUtil.encoder(value));
		cookie.setMaxAge(seconds);
		if (StringUtil.isNotEmpty(path)) {
			cookie.setPath(path);
		}
		response.addCookie(cookie);
	}

	public static void removeCookie(HttpServletResponse response, String key) {
		removeCookie(response, key, null);
	}

	public static void removeCookie(HttpServletResponse response, String key, String path) {
		Cookie[] cookies = SpringUtil.getRequest().getCookies();
		if (cookies != null)
			for (int i = 0; i < cookies.length; ++i) {
				Cookie cookie = cookies[i];
				if (cookie.getName().equals(key)) {
					cookie.setMaxAge(0);
					if (StringUtil.isNotEmpty(path)) {
						cookie.setPath(path);
					}
					response.addCookie(cookie);
					return;
				}
			}
	}

	@Deprecated
	public static String getIp() {
		HttpServletRequest request = SpringUtil.getRequest();
		if (request == null) {
			return "";
		}
		String str1 = request.getHeader("x-forwarded-for");
		String str2 = request.getHeader("http_client_ip");
		String str3 = "unknown";
		if ((str1 != null) && (!(str1.equalsIgnoreCase(str3))) && (str1.trim().length() > 0))
			return str1;
		if ((str2 != null) && (!(str2.equalsIgnoreCase(str3))) && (str2.trim().length() > 0)) {
			return str2;
		}
		return request.getRemoteAddr();
	}

	/**
	 * path
	 * 
	 * @param path
	 * @return
	 */
	public static String getAbsolutePath(String path) {
		if (StringUtil.isEmpty(path)) {
			return path;
		}
		if (path.startsWith("/"))
			path = BaseInfo.getContextPath() + path;
		else {
			path = BaseInfo.getContextPath() + "/" + path;
		}
		return path;
	}
}
